
<!-- 框架 -->
<template>
  <div class="container flex">
    <div :class="menuCollapse ? 'collapse' : ''" class="left-container flex-column transition">
      <div :class="menuCollapse ? 'collapse' : ''" class="user-wrap">
        <!--        <img class="transition" src="/static/images/ic_touxiang_120x120.png" alt="">-->
        <p v-if="!menuCollapse">欢迎.{{ username }}</p>
        <p v-else style="opacity: 1">{{ username }}</p>
      </div>
      <div class="left-menu">
        <el-menu :collapse="menuCollapse" :collapse-transition="false" background-color="#ffffff"
          active-text-color="#337ED0" unique-opened @select="menuSelect">
          <!-- router -->
          <template v-for="(item,index) in menuList">
            <!-- 父 -->
            <el-menu-item v-if="!item.list || !item.list.length" :key="item.menuId" :index="index + '_' + item.menuId">
              <i :class="item.icon"></i>
              <span slot="title">{{ item.name }}</span>
            </el-menu-item>
            <el-submenu :index="index + '_' + item.menuId" v-if="item.menuId !== 99" :key="item.menuId">
              <template slot="title">
                <i :class="item.icon"></i>
                <span class="span-to">{{ item.name }}</span>
              </template>
              <!-- 子 -->
              <el-menu-item-group v-for="(it,indexs) in item.list">
                <el-menu-item :index="indexs + '_' + it.menuId" :key="it.menuId">
                  <i :class="it.icon"></i>
                  <span>{{ it.name }}</span>
                </el-menu-item>
              </el-menu-item-group>
            </el-submenu>
          </template>
        </el-menu>
      </div>
    </div>
    <div class="flex-item over-hidden">
      <div class="main-content flex-column">
        <div class="main-header flex">
          <div :class="menuCollapse ? 'open' : ''" class="toggle-img" @click="menuCollapse = !menuCollapse"></div>
          <div class="flex-item over-hidden">
            <el-tabs v-model="activeTab" class="header-tabs" closable type="card" @tab-remove="removeTab"
              @tab-click="toggleTab">
              <el-tab-pane v-for="item in menuTabs" :key="item.menuId" :label="item.name" :name="'' + item.menuId"></el-tab-pane>
            </el-tabs>
          </div>

          <!-- <div class="system-title" style="text-decoration: none;color: white; font-size:12px" @click="linkToMap">统计</div> -->
          <div class="flex-center">
            <el-popover placement="bottom" title="待审核住户" trigger="click">
              <el-table :data="houseHoldApplyList">
                <el-table-column label="姓名" property=title width="100"></el-table-column>
                <el-table-column label="审核状态" width="80">
                  <template slot-scope="scope">
                    <span v-if="scope.row.applyStatus === 1" class="text-green">已通过</span>
                    <span v-else-if="scope.row.applyStatus === 2" class="text-red">已拒绝</span>
                    <span v-else class="text-red">待审核</span>
                  </template>
                </el-table-column>
                <el-table-column label="申请时间" property="createDate" width="130"></el-table-column>
              </el-table>
              <div style="margin-top: 5px">
                <el-button type="primary" @click="showMore">查看更多</el-button>
              </div>
              <el-badge slot="reference" :hidden="!totalCount" :value="totalCount" :max="99" class="item">
                <i class="el-icon-message-solid" style="color: white;"></i>
              </el-badge>
            </el-popover>
          </div>
          <div class="flex-center">
            <el-dropdown trigger="click" @command="dropdownCommand">
              <span class="el-dropdown-link">
                <i class="el-icon-s-tools" style="margin-right: 15px;color: white;">
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="editPassword" icon="el-icon-edit">修改密码</el-dropdown-item>
                <el-dropdown-item command="exit" icon="el-icon-switch-button">退出系统</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
          <!-- <keep-alive> -->
            <div class="main-view flex-item">
              <router-view/>
            </div>
          <!-- </keep-alive> -->
      </div>
    </div>

    <el-dialog :visible="dialogVisible" title="修改密码" width="330px" @close="dialogVisible = false">
      <el-form label-position="right" label-width="80px">
        <el-form-item label="原始密码" required>
          <el-input v-model="saveForm.password" placeholder="请输入原始密码" size="small"></el-input>
        </el-form-item>
        <el-form-item label="新密码" required>
          <el-input v-model="saveForm.newPassword" placeholder="请输入新密码" size="small"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="btn btn-default" @click="dialogVisible = false">取 消</el-button>
        <el-button class="btn btn-blue" type="primary" @click="onUpdatePassword()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updatePwd } from '../api/componentsApi/api'
export default {
  computed: {

  },
  data () {
    return {
      dialogVisible: false,
      activePath: '/',
      buildingPosition: '',
      menuCollapse: false,
      menuList: [
        { menuId: 99, icon: 'el-icon-s-home', name: '首页', url: 'index' },
        {
          menuId: 100,
          icon: 'el-icon-user-solid',
          name: '用户管理',
          list: [
            { menuId: 101, name: '维修人员管理', url: 'repairUserManage' }
          ]
        },
        {
          menuId: 1,
          icon: 'el-icon-user-solid',
          name: '客户管理',
          list: [
            { menuId: 2, name: '客户信息管理', url: 'clientInfo' },
            { menuId: 3, name: '客户资产管理', url: 'clientAssets' }
          ]
        },

        {
          menuId: 4,
          icon: 'el-icon-s-finance',
          name: '资产管理',
          list: [
            { menuId: 5, name: '资产管理', url: 'assetsManage' },
            { menuId: 6, name: '资产类型管理', url: 'assetsTypeManage' },
            { menuId: 7, name: '资产关系管理', url: 'assetsBearingManage' }
          ]
        },

        {
          menuId: 8,
          icon: 'el-icon-s-check',
          name: '事件报警',
          list: [
            { menuId: 9, name: '事件报警汇总', url: 'alarmProcessSet' },
            { menuId: 52, name: '猫狗报警', url: 'catDogAlarm' },
            { menuId: 10, name: '电动车报警', url: 'electricVehicleAlarm' },
            { menuId: 12, name: '火情报警', url: 'fireAlarm' },
            { menuId: 53, name: '高抛报警', url: 'highThrowAlarm' }
          ]
        },

        {
          menuId: 13,
          icon: 'el-icon-s-ticket',
          name: '设备管理',
          list: [
            { menuId: 14, name: '门禁主机', url: 'deviceSwitchControl' },
            { menuId: 15, name: '摄像头管理', url: 'deviceDataSending' }
          ]
        },

        {
          menuId: 16,
          icon: 'el-icon-s-claim',
          name: '设备查询',
          list: [
            { menuId: 17, name: '设备分类', url: 'deviceClass' }
            // { menuId: 18, name: "设备查询", url: "deviceQuery" },
            // { menuId: 19, name: "设备状态查询", url: "deviceTypeQuery" },
            // { menuId: 20, name: "设备明细", url: "deviceDetailed" },
          ]
        },

        {
          menuId: 21,
          icon: 'el-icon-s-marketing',
          name: '设备周期管理',
          list: [
            { menuId: 22, name: '设备周期设置', url: 'deviceCycleSet' },
            { menuId: 23, name: '运维记录', url: 'devOpsRecord' },
            { menuId: 24, name: '更新记录', url: 'updateRecord' },
            { menuId: 25, name: '设备超期统计', url: 'deviceOverdueCensus' }
          ]
        },

        {
          menuId: 26,
          icon: 'el-icon-s-opportunity',
          name: '工单管理',
          list: [
            { menuId: 27, name: '工单规则管理', url: 'workOrderTriggerSet' },
            { menuId: 28, name: '工单流程设置', url: 'workOrderProcessManage' },
            { menuId: 29, name: '工单任务管理', url: 'workOrderManage' }
          ]
        },
        {
          menuId: 50,
          icon: 'el-icon-s-opportunity',
          name: '工单管理（小程序）',
          list: [
            { menuId: 43, name: '工单管理', url: 'workOrderManages' },
            { menuId: 44, name: '工单审核管理', url: 'workOrderApprovalManages' },
            { menuId: 45, name: '巡检任务管理', url: 'patrolTaskManage' },
            { menuId: 46, name: '巡检任务列表', url: 'patrolTaskList' },
            { menuId: 47, name: '知识库管理', url: 'KnowledgeBaseManage' },
            { menuId: 48, name: '备件仓库管理', url: 'warehouseManage' }
          ]
        },
        {
          menuId: 30,
          icon: 'el-icon-s-order',
          name: '运维管理',
          list: [
            // { menuId: 31, name: "远程固件更新", url: "remoteFirmwareUpdate" },
            // { menuId: 32, name: "远程配置更新", url: "remoteConfigUpdate" },
            { menuId: 33, name: '运维工单分配', url: 'devOpsWorkOrderDistri' }
          ]
        },

        // {
        //   menuId: 34, icon: 'el-icon-s-data', name: "数据报表",
        //   list: [
        //     { menuId: 35, name: "资产汇总", url: "assetsSummary" },
        //     { menuId: 36, name: "客户汇总", url: "customerSummary" },
        //     { menuId: 37, name: "设备汇总", url: "deviceSummary" },
        //     { menuId: 38, name: "设备状态汇总", url: "deviceTypeSummary" },
        //     { menuId: 39, name: "设备报警汇总", url: "devicealarmSummary" },
        //   ],
        // },

        {
          menuId: 40,
          icon: 'el-icon-s-order',
          name: '设备日志',
          list: [
            { menuId: 41, name: '设备日志配置', url: 'deviceLogConfig' },
            { menuId: 42, name: '设备状态日志查询', url: 'deviceTypeLogQuery' }
            // { menuId: 43, name: "设备状态日志明细", url: "deviceTypeLogDetailed" },
          ]
        }
      ],
      menuTabs: [],
      menuTabIds: [],
      activeMenu: '',
      activeTab: '',
      viewBg: '',
      username: '用户名',
      saveForm: {
        password: null,
        newPassword: null
      },
      messageVisible: false,
      houseHoldApplyList: [],
      totalCount: 0
    }
  },
  created () {
    this.initTabs()
    const route = this.$route
    const persistence = this.$store.getters.getPersistence
    if (persistence.token) {
      this.username = persistence.username
      this.getMenu()
    } else {
      // 跳转到登录页面
      this.$router.push({ name: 'login', query: route.query })
    }
    if (this.$route.name !== 'index') {
      this.viewBg = 'bg-white'
    } else {
      this.viewBg = ''
    }
    // this.getHouseHoldApplyList();
    // setInterval(() => {
    //   this.getHouseHoldApplyList();
    // }, 60000)
  },
  beforeRouteUpdate (to, from, next) {
    if (to.name !== 'index') {
      this.viewBg = 'bg-white'
    } else {
      this.viewBg = ''
    }
    next()
  },
  methods: {
    linkToMap () {
      // window.open('/static/menjingzhushou/index.html');
      // 跳转到统计
      // window.location.href = '/static/menjingzhushou/index.html'
    },
    linkTo (index) {
      const path = this.menuList[index].url
      this.activePath = path
      this.$router.push({ path: path, query: { buildingId: this.buildingId } })
    },
    getMenu () {
      // this.req.get('sys/menu/nav').then(res => {
      //   let list = [];
      //   res.menuList.map(item => {
      //     if (item.isShow) {
      //       if (item.list && item.list.length > 0) {
      //         let subList = item.list;
      //         item.list = [];
      //         subList.map(subItem => {
      //           if (subItem.isShow && subItem.url) {
      //             item.list.push(subItem)
      //           }
      //         });
      //         if (item.list.length > 0) {
      //           list.push(item);
      //         }
      //       } else if (item.url) {
      //         list.push(item);
      //       }
      //     }
      //   });
      //   window.permissions = res.permissions
      //   // localStorage.setItem('permissions', res.permissions)
      //   this.menuList = list;
      // }).catch(e => {
      // })
    },
    getBuilding () {
      // this.req.get('/sys/building/info/' + this.buildingId).then(res => {
      //   let building = {
      //     estateName: res.building.estateName,
      //     estateId: res.building.estateId,
      //     buildingName: res.building.buildingName,
      //     buildingId: res.building.buildingId,
      //     alleyId: res.building.alleyId,
      //     alleyName: res.building.alleyName,
      //   };
      //   this.$store.commit('setBuilding', building);
      //   this.buildingPosition = building.estateName + building.alleyName + building.buildingName;
      //   this.getMenu();
      // }).catch(e => {
      // })
    },
    menuSelect (index, indexPath) {
      const itemIndex = index.split('_')[0]
      let item
      if (indexPath.length > 1) {
        const parentIndex = indexPath[0].split('_')[0]
        item = this.menuList[parentIndex].list[itemIndex]
      } else {
        item = this.menuList[itemIndex]
      }
      this.toggleMenu(item, itemIndex)
    },
    toggleMenu (pathItem, index) {
      if (pathItem === null) {
        this.$router.push({ path: '/index' })
        return
      }
      const pathArr = pathItem.url.split('/')
      pathItem.pathname = pathArr[pathArr.length - 1]
      this.activeMenu = index + '_' + pathItem.menuId
      this.$router.push({ path: pathItem.url })
      this.addTab(pathItem, index)
    },
    // 初始化tabs
    initTabs () {
      const tabData = JSON.parse(window.sessionStorage.getItem('ROUTER_TABS')) || {}
      this.menuTabs = tabData.list || []
      this.menuTabIds = tabData.ids || []
      this.activeTab = tabData.current || ''
    },
    // 保存tabs在sessionStorage
    saveTabs () {
      const tabs = {
        list: this.menuTabs,
        ids: this.menuTabIds,
        current: this.activeTab
      }
      window.sessionStorage.setItem('ROUTER_TABS', JSON.stringify(tabs))
    },
    // 增加标签页
    addTab (pathItem, index) {
      this.activeTab = String(pathItem.menuId)
      if (pathItem.url === 'index') return
      let has = false
      this.menuTabIds.forEach(item => {
        if (item.indexOf('_' + this.activeTab) > -1) {
          has = true
        }
      })
      if (!has) {
        this.menuTabs.push(pathItem)
        this.menuTabIds.push(index + '_' + this.activeTab)
      }
      this.saveTabs()
    },
    // 删除标签页
    removeTab (menuId) {
      let nextIndex = 0
      const currentIndex = this.menuTabs.findIndex(el => {
        return el.menuId == menuId
      })

      if (currentIndex >= 0) {
        // 换到旁边的标签页
        if (this.activeTab == this.menuTabIds[currentIndex].split('_')[1]) {
          nextIndex = currentIndex + 2 <= this.menuTabs.length
            ? currentIndex + 1
            : (currentIndex - 1 >= 0
                ? currentIndex - 1
                : null)

          nextIndex === null
            ? this.toggleMenu(null)
            : this.toggleMenu(this.menuTabs[nextIndex], this.menuTabIds[nextIndex].split('_')[0])
        }

        this.menuTabs.splice(currentIndex, 1)
        this.menuTabIds.splice(currentIndex, 1)
        this.saveTabs()
      }
    },
    // 切换标签页
    toggleTab (instance) {
      this.toggleMenu(this.menuTabs[instance.index], this.menuTabIds[instance.index].split('_')[0])
    },
    // 退出登录
    logout () {
      this.$store.commit('clean')
      this.$router.push({ name: 'login' })
    },
    onShowUpdateDialog () {
      this.dialogVisible = true
      this.saveForm = {
        password: null,
        newPassword: null
      }
    },
    // 修改密码
    onUpdatePassword () {
      updatePwd(this.saveForm).then(res => {
        this.dialogVisible = false
        this.$message({
          message: '修改成功',
          type: 'success',
          showClose: true
        })
      })
    },

    // 用户提示，小提示框
    // getHouseHoldApplyList () {
    //   const obj = {
    //     page: 1,
    //     limit: 10,
    //     applyStatus: 0,
    //     sidx: 'apply_status asc,',
    //     order: 'create_time desc'
    //   }
    //   this.req.get('/sys/householdapply/list', { params: obj }).then(res => {
    //     this.totalCount = res.page.totalCount
    //     this.houseHoldApplyList = res.page.list
    //   }).catch(e => {

    //   })
    // },

    showMore () {
      const item = {
        menuId: 171,
        parentId: 40,
        parentName: null,
        title: '用户申请',
        url: '/householdApply',
        perms: 'sys:householdapply:list,sys:householdapply:delete,sys:householdapply:info,sys:householdapply:save,sys:householdapply:update',
        type: 1,
        icon: 'fa fa-crosshairs',
        orderNum: 3,
        open: null,
        list: null,
        isShow: 1,
        pathname: 'householdApply'
      }
      this.addTab(item, 1)
      this.$router.push({ path: '/householdApply', query: {} })
    },
    dropdownCommand (e) {
      switch (e) {
        case 'editPassword':
          this.onShowUpdateDialog()
          break
        case 'exit':
          this.logout()
          break
      }
    }
  }
}
</script>

<style scoped>
.item {
  margin-top: 0px;
  margin-right: 20px;
}

.container {
  height: 100vh;
}
</style>
